﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
using Yonkly.Models;
using Yonkly.Utility;
using Yonkly.Services;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security;

namespace Yonkly.Controllers
{
    public class TwitterFriendsController : BaseController
    {

        protected override void HandleUnknownAction(string actionName)
        {
            RedirectToAction("Index");
        }

        #region Invite Twitter Friends
        public ActionResult Invite(string twitterusername)
        {
            var result = new Yonkly.Models.JsonResult();
            try
            {
                SendMessageToTwitterUser(twitterusername);
                result.isSuccessful = true;
            }
            catch (Exception ex)
            {
                result.isSuccessful = false;
                result.errorMessage = ex.Message;
            }
            return View("Json", result);
        }


        private void SendMessageToTwitterUser(string twitterUserName)
        {
            try
            {
                string message;
                var us = ProfileController.GetUserSettings(LoggedInUserId);
                string file = System.Web.HttpContext.Current.Server.MapPath("~/content/MailTemplates/TwitterDirectMessage.txt");
                message = File.ReadAllText(file);
                message = message.Replace("<%twittername%>", twitterUserName);
                message = message.Replace("<%myurl%>", "http://yonkly.com/" + LoggedInUserName);
                if (!string.IsNullOrEmpty(us.TwitterUserName) && !string.IsNullOrEmpty(us.TwitterPassword))
                {
                    Twitter tw = new Twitter();
                    var xml = tw.UpdateAsXML(us.TwitterUserName, us.TwitterPassword, message);
                }
            }
            catch (Exception e)
            {
                Utils.Log(e);
            }

        }
        //private void SendDirectMessage(string twitterusername)
        //{
        //    string msgBody;
        //    var us = ProfileController.GetUserSettings(LoggedInUserId);
        //    string passwordPre = us.TwitterPassword;
        //    char[] passwordChars = passwordPre.ToCharArray();
        //    SecureString password = new SecureString();
        //    foreach (char c in passwordChars)
        //    {
        //        password.AppendChar(c);
        //    }

        //    try
        //    {
        //        Twitter tw = new Twitter();
        //        string file = System.Web.HttpContext.Current.Server.MapPath("~/content/MailTemplates/TwitterDirectMessage.txt");
        //        msgBody = File.ReadAllText(file);
        //        msgBody = msgBody.Replace("<%friend%>", us.Name);
        //        msgBody = msgBody.Replace("<%friendurl%>", "http://yonkly.com/" + LoggedInUserName);
        //        tw.SendDirectMessagetoTwitter(us.TwitterUserName, us.TwitterPassword, twitterusername, msgBody);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
        #endregion

        #region View Twitter Friends
        //BaseViewData with Twitter Friends
        private BaseViewData GetBaseViewDataByTwitterPage(int? page) //new
        {
            Twitter tw = new Twitter();
            var us = ProfileController.GetUserSettings(LoggedInUserId);
            BaseViewData baseViewData = GetBaseViewData();
            if (!string.IsNullOrEmpty(us.TwitterUserName))
            {
                string json = tw.GetFriendsAsJSON(us.TwitterUserName, us.TwitterPassword);
                json = @"{""TwitterFriends"":" + json + "}";
                //To skip the protected keyword
                json = json.Replace(@",""protected"":", @",""_protected"":");

                TwitterFriendsViewData tf = JsonHelper.Deserialize<TwitterFriendsViewData>(json);

                IList<UserSetting> usList = GetAllTwitterUserSettings();
                //Join TwitterFirnds with yonkly users having twitter user name
                var query = tf.TwitterFriends.Join(usList, twf => twf.screen_name, tu => tu.TwitterUserName,
                    (twf, tu) => twf);
                baseViewData.TwitterFriends = tf.TwitterFriends.Except(query.ToList<TwitterFriendItem>())
                                                      .AsQueryable<TwitterFriendItem>().ToPagedList((int)page, Globals.PageSize);
            }
            return baseViewData;
        }


        public ActionResult Index(int? page)
        {
            page = page ?? 0;
            var us = ProfileController.GetUserSettings(LoggedInUserId);
            if (LoggedInUserId != null && LoggedInUserId != Guid.Empty)
            {
                if (us.TwitterUserName != null && us.TwitterUserName != string.Empty)
                {
                    BaseViewData baseViewData = GetBaseViewDataByTwitterPage(page);
                    //Todo:Use Lamda expression to filter out the existing users of yoknly from the TwitterFriends
                    return View("Index", baseViewData);
                }
                else
                {
                    return View("Index", GetBaseViewData());
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        #endregion


        [NonAction]
        public IList<UserSetting> GetAllTwitterUserSettings()
        {
            using (var dc = new YonklyDataContext())
            {
                var query = dc.UserSettings.Where(us => us.TwitterUserName != null);
                return query.ToList<UserSetting>();
            }
        }
    }
}
